package com.zhl.projectmerger;

import com.zhl.projectmerger.strategy.ControllerMergeStrategy;
import com.zhl.projectmerger.strategy.DefaultMergeStrategy;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;


import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DefaultMergerStrategyRegister implements MergerStrategyRegister {
    Set<MergeStrategy> strategies = new HashSet<>();

    {
        strategies.add(new ControllerMergeStrategy());
    }

    @Override
    public void regist(MergeStrategy strategy) {
        strategies.add(strategy);
    }

    @Override
    public void regist(List<MergeStrategy> strategies) {
        strategies.addAll(strategies);
    }

    @Override
    public void unRegister(MergeStrategy strategy) {
        strategies.remove(strategy);
    }

    @Override
    public void unRegist(List<MergeStrategy> strategies) {
        strategies.removeAll(strategies);
    }

    /**
     * 根据给定的源类描述、目标类描述和合并配置选择合并策略。
     *
     * @param fromClass 源类描述，需要进行合并的类
     * @param toClass   目标类描述，合并后的类
     * @param mergerConfig 合并配置
     * @return 合并策略，如果匹配到则返回对应的合并策略，否则返回null
     */
    @Override
    public MergeStrategy selectMergeStrategy(ClassOrInterfaceDeclaration fromClass,
                                             ClassOrInterfaceDeclaration toClass,
                                             ProjectMergeConfig mergerConfig) {

        MergeStrategy result = new DefaultMergeStrategy();
        for (MergeStrategy strategy : strategies) {
            if (strategy.match(fromClass, toClass, mergerConfig)) {
                return result = strategy;
            }
        }

        if (result.match(fromClass, toClass, mergerConfig)) {
            return result;
        } else {
            return null;
        }
    }
}
